package com.atguigu.gulimall.gateway.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 用于维护 跨域 相关的配置，解决跨域问题
 */
@Configuration
public class GulimallCorsConfigConfiguration {

    /**
     * 构建允许跨域的配置
     * @return
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1、配置跨域
        corsConfiguration.addAllowedOrigin("*");    // 允许任何域名
        corsConfiguration.addAllowedHeader("*");    // 允许任何头
        corsConfiguration.addAllowedMethod("*");    // 允许任何方法
        corsConfiguration.setAllowCredentials(true);    // 允许携带Cookie
        return corsConfiguration;
    }

    /**
     * 使用跨域过滤器，注册加载配置
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", this.buildConfig());     // 注册，对任何路径的请求都加上跨域参数
        return new CorsWebFilter(source);
    }
}
